package com.zykj.thread.traditional;

/**
 * @author zhoulj(周利军) [1217102780@qq.com]
 * @Module ID:   <(模块)类编号，可以引用系统设计中的类编号>
 * @Comments: <多线程对共享数据的操作>
 * @JDK version used:      <JDK1.8> 19
 * @since 2019/1/15-10:19
 */
public class ThreadShareData {

    public static void main(String[] args) throws InterruptedException {
        ShareData shareData = new ShareData();
        for (int i = 0; i < 3; i++) {

            ThreadInc threadInc = new ThreadInc(shareData);
            new Thread(threadInc).start();

            ThreadDec threadDec = new ThreadDec(shareData);
            new Thread(threadDec).start();

        }
//
//        Thread.currentThread().join();
        System.out.println(Thread.activeCount());
        if(Thread.activeCount()==1)
        System.out.println("execute Finish！   j="+shareData.j);
    }

}

class ShareData {
    int j = 10;

    public synchronized void dec() {
        j--;
        System.out.println(Thread.currentThread().getName()+"--减操作..."+j);
    }
    public synchronized void inc() {
        j++;
        System.out.println(Thread.currentThread().getName()+"--加操作..."+j);
    }
}
class ThreadInc implements Runnable {

    ShareData shareData;
    public ThreadInc(ShareData shareData) {
        this.shareData = shareData;
    }

    public void run() {
        shareData.inc();
    }
}
class ThreadDec implements Runnable {
    ShareData shareData;
    public ThreadDec(ShareData shareData) {
        this.shareData = shareData;
    }

    public void run() {
        shareData.dec();
    }
}